/**
 * 特殊装备状态管理模块
 */

import * as specialApi from '@/api/specialEquipment'

const state = {
  list: [],
  loading: false,
  error: null
}

const mutations = {
  SET_LIST(state, list) { state.list = Array.isArray(list) ? list : [] },
  SET_LOADING(state, loading) { state.loading = !!loading },
  SET_ERROR(state, error) { state.error = error || null },
  UPDATE_ITEM(state, item) {
    const idx = state.list.findIndex(i => i.id === item.id)
    if (idx >= 0) state.list.splice(idx, 1, item)
    else state.list.unshift(item)
  }
}

const actions = {
  async loadList({ commit }) {
    commit('SET_LOADING', true); commit('SET_ERROR', null)
    try {
      const resp = await specialApi.listSpecialEquipments({})
      commit('SET_LIST', resp.data || [])
      return resp.data || []
    } catch (e) {
      commit('SET_ERROR', e.message || '加载失败')
      return []
    } finally { commit('SET_LOADING', false) }
  },
  async acquire({ commit }, { type, tier, name_index }) {
    commit('SET_LOADING', true); commit('SET_ERROR', null)
    try {
      const resp = await specialApi.acquireSpecialEquipment({ type, tier, name_index })
      if (resp && resp.data) commit('UPDATE_ITEM', resp.data)
      return resp.data
    } catch (e) {
      commit('SET_ERROR', e.message || '获取失败')
      return null
    } finally { commit('SET_LOADING', false) }
  },
  async equip({ commit }, { type }) {
    commit('SET_LOADING', true); commit('SET_ERROR', null)
    try {
      const resp = await specialApi.equipSpecialEquipment({ type })
      if (resp && resp.data) commit('UPDATE_ITEM', resp.data)
      return resp.data
    } catch (e) {
      commit('SET_ERROR', e.message || '穿戴失败')
      return null
    } finally { commit('SET_LOADING', false) }
  },
  async unequip({ commit }, { type }) {
    commit('SET_LOADING', true); commit('SET_ERROR', null)
    try {
      const resp = await specialApi.unequipSpecialEquipment({ type })
      if (resp && resp.data) commit('UPDATE_ITEM', resp.data)
      return resp.data
    } catch (e) {
      commit('SET_ERROR', e.message || '卸下失败')
      return null
    } finally { commit('SET_LOADING', false) }
  }
}

const getters = {
  equippedItems: (state) => state.list.filter(i => i.equipped),
  byType: (state) => (type) => state.list.filter(i => i.type === type)
}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}